package com.bds.btcdc.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bds.btcdc.adapter.huobi.trade.HuobiClient;
import com.bds.btcdc.adapter.huobi.trade.model.HuobiAccount;
import com.bds.btcdc.config.NutzDaoConfig;
import com.bds.btcdc.model.UserKeys;
import com.bds.btcdc.util.Const;
import com.bds.btcdc.util.DESUtil;
import org.apache.commons.lang.StringUtils;
import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.nutz.dao.Sqls;
import org.nutz.dao.sql.Sql;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by DongChenchen on 2018/5/8 0008
 */
@Service
public class UserKeysService {
    private static final Charset CHARSET = Charset.forName("utf-8");
    @Autowired
    private NutzDaoConfig dao;
    public UserKeys getByUserIdAndExchange(Long user_id,String exchange){
        Sql sql= Sqls.create("select a.* from t_user_keys a " +
                "where a.user_id=@user_id " +
                "and a.exchange=@exchange");
        sql.setParam("user_id",user_id);
        sql.setParam("exchange",exchange);
        sql.setCallback(Sqls.callback.entity());
        sql.setEntity(dao.getEntity(UserKeys.class));
        dao.execute(sql);
        UserKeys keys = sql.getObject(UserKeys.class);
        try {
            String access_key = DESUtil.decrypt(keys.getAccess_key(), CHARSET, Const.DESKEY);
            String secret_key = DESUtil.decrypt(keys.getSecret_key(), CHARSET, Const.DESKEY);
            keys.setAccess_key(access_key);
            keys.setSecret_key(secret_key);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return keys;
    }

    /**
     * huobi api需要内部id，若id为空，需初始化
     * @param user_id
     * @return
     */
    public UserKeys getHuobiKeys(Long user_id){
        Sql sql= Sqls.create("select a.* from t_user_keys a " +
                "where a.user_id=@user_id " +
                "and a.exchange='HUOBI'");
        sql.setParam("user_id",user_id);
        sql.setCallback(Sqls.callback.entity());
        sql.setEntity(dao.getEntity(UserKeys.class));
        dao.execute(sql);
        UserKeys keys = sql.getObject(UserKeys.class);
        String access_key;
        String secret_key;
        try {
            access_key = DESUtil.decrypt(keys.getAccess_key(), CHARSET, Const.DESKEY);
            secret_key = DESUtil.decrypt(keys.getSecret_key(), CHARSET, Const.DESKEY);
            keys.setAccess_key(access_key);
            keys.setSecret_key(secret_key);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        String account_id=keys.getExtra_id();
        if(StringUtils.isEmpty(account_id)){
            HuobiClient client=HuobiClient.getInstance(user_id,access_key,secret_key,null);
            String data = client.getAccounts();
            JSONObject obj=JSONObject.parseObject(data);
            JSONArray account_list=obj.getJSONArray("data");
            List<HuobiAccount> list=account_list.toJavaList(HuobiAccount.class);
            account_id=String.valueOf(list.get(0).getId());
            dao.update(UserKeys.class,Chain.make("extra_id",account_id), Cnd.where("user_id","=",user_id).and("exchange","=","HUOBI"));
        }
        keys.setExtra_id(account_id);
        return keys;
    }

    public List<UserKeys> getByUserId(Long user_id){
        Sql sql= Sqls.create("select a.* from t_user_keys a " +
                "where a.user_id=@user_id ");
        sql.setParam("user_id",user_id);
        sql.setCallback(Sqls.callback.entities());
        sql.setEntity(dao.getEntity(UserKeys.class));
        dao.execute(sql);
        List<UserKeys> keyss = sql.getList(UserKeys.class);
        if(!CollectionUtils.isEmpty(keyss)) {
            try {
                for(UserKeys keys:keyss) {
                    if (keys.getExchange().equals(Const.HUOBI.EXCHANGE)){
                        keyss.remove(keys);
                        keys=getHuobiKeys(user_id);
                        keyss.add(keys);
                    }else if (keys != null && StringUtils.isNotEmpty(keys.getAccess_key()) && StringUtils.isNotEmpty(keys.getAccess_key())) {
                        String access_key = DESUtil.decrypt(keys.getAccess_key(), CHARSET, Const.DESKEY);
                        String secret_key = DESUtil.decrypt(keys.getSecret_key(), CHARSET, Const.DESKEY);
                        keys.setAccess_key(access_key);
                        keys.setSecret_key(secret_key);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return keyss;
    }
}
